var app = require('express')();
const bodyParser = require('body-parser')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
const stringRandom = require('string-random');
const nodemailder = require("nodemailer");
var renshu = 0;

// 使用express托管静态资源
app.use(require('express').static('public'));
// 配置解析请求参数的中间件（por请求/）
app.use(bodyParser.urlencoded({ extended: false }))
// 将数据转换成json格式
app.use(bodyParser.json())

// 对于处理首页的路由
app.get('/', function (req, res) {
  // 重定向到index.html
  res.redirect('lempChat.html');
});

/* 数据存储和获取 start */
app.get('/get', function (req, res) {
  let { target } = req.query;
  if (target && global[target]) { res.json(global[target]) }
  else { res.json([]) }
});
app.post('/set', function (req, res) {
  let { target } = req.query;
  if (target) {
    global[target] = req.body;
    res.json('success');
  }
  else { res.json('fail') }
});
/* 数据存储和获取 end */

/* 发送邮箱 start */
const transPort = nodemailder.createTransport({
  service: 'qq', host: 'smtp.qq.com', port: 456, secure: true,
  auth: { pass: "wwgehaimzctpicic", user: "wu.wei.jun@qq.com" }
})
app.get('/nodemailder', function (req, res) {
  if (!connections['18820651349'])
    transPort.sendMail({
      from: "wu.wei.jun@qq.com", to: "wu.wei.jun@qq.com", subject: "来信息啦", text: ""
    }, (error, result) => { if (error) { res.end('fail') } else { res.end('success') } })
  else { res.status(200); res.send('完成'); }
});
/* 发送邮箱 end */

const connections = {}; // 存储连接的映射  
io.on('connection', function (socket) {
  // 存储连接状态  
  const id = socket.handshake.query.id; // 从查询参数中获取ID 
  connections[id] = socket;

  // 用户连接
  renshu++;
  io.emit('renshu', renshu);

  socket.on('disconnect', function (data) {
    // 连接断开时移除连接状态  
    delete connections[id];

    // 用户断开
    renshu--;
    io.emit('renshu', renshu);
  });

  // 关闭其他用户
  socket.on('closeUsers', (data) => {
    // console.log(data);
    io.emit('closeUsers', data);
  });

  // 进行消息广播
  socket.on('sendMessage', (data) => {
    io.emit('sendMessage', data);
  });

  // 进行图片消息广播
  socket.on('sendimage', (data) => {
    io.emit('sendimage', data);
  });
});

// 服务器监听端口,可修改
http.listen(4321, function () {
  console.log("运行成功，正在监听4321端口");
});
